package com.ysy.logistics.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysy.common.resp.ResultData;
import com.ysy.common.resp.ReturnCodeEnum;
import com.ysy.common.util.SaltMD5Util;
import com.ysy.logistics.entities.oam.LoginLog;
import com.ysy.logistics.entities.system.SysUser;
import com.ysy.logistics.entities.system.dto.SysUserDTO;
import com.ysy.logistics.entities.system.vo.LoginVO;
import com.ysy.logistics.entities.system.vo.RegisterVO;
import com.ysy.logistics.entities.system.vo.RestInfoVo;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.oam.LoginLogService;
import com.ysy.logistics.service.system.SysUserService;
import com.ysy.logistics.service.system.UserRoleService;
import com.ysy.logistics.util.IPUtils;
import com.ysy.logistics.util.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/12 15:00
 **/
@Slf4j
@RestController
@RequestMapping(value = "/sysUser",name = "用户")
@CrossOrigin
@Tag(name = "用户管理",description = "user表的CRUD")
public class SysUserController {


    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private LoginLogService loginLogService;



    @PostMapping("/login")
    @Operation(summary = "登录",description = "用户登录")
    public ResultData<SysUserDTO> loginByUserName(@RequestBody LoginVO loginVO){
        //保存日志
        ResultData<SysUserDTO> login = sysUserService.login(loginVO);
        String ipAddress = IPUtils.getIpAddress(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        //构建登录日志
        LoginLog loginLog = new LoginLog().setLogName("登录日志").setIp(ipAddress).setCreateTime(new Date());
        if (login.successFlag()){
            loginLog = loginLog.setSucceed("成功").setUserId(login.getData().getId()).setUserName(login.getData().getUsername());
        }else {
            loginLog = loginLog.setSucceed("失败").setMessage(login.getMessage()).setUserName(loginVO.getAccount());
        }
        log.info("登录日志：{}",loginLog);
        loginLogService.save(loginLog);
        return login;
    }


    @PostMapping("/register")
    @Operation(summary = "注册",description = "注册用户")
    @OperateLog("添加用户")
    public ResultData<SysUserDTO> register( @RequestBody @Validated RegisterVO registerVO){
        return sysUserService.register(registerVO);
    }

    @GetMapping("/logOut")
    @Operation(summary = "退出登录",description = "退出登录")
    public ResultData<String> logOut(){
        StpUtil.logout();
        return ResultData.success("退出成功");
    }

    @GetMapping("/checkUserName/{userName}")
    @Operation(summary = "校验用户名",description = "校验用户名是否可以使用")
    public ResultData<String> checkUserName(@PathVariable("userName") String userName){
        log.info("用户名:{}",userName);
        SysUser sysUser =new SysUser();
        sysUser.setUsername(userName);
        return sysUserService.existsBySysUser(sysUser).successFlag()?ResultData.fail("该用户名已被使用"): ResultData.success("该用户名未被使用");

    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息",description = "获取用户信息")
    public ResultData<SysUserDTO> getUserInfo(){
        //是否登录
        if (!StpUtil.isLogin()){
            return ResultData.fail("未登录");
        }
        String userId = StpUtil.getLoginId().toString();
        return sysUserService.getUserInfoById(userId);
    }

    @PostMapping("/listByPage")
    @Operation(summary = "分页查询用户",description = "分页查询用户")
    @OperateLog("查询用户")
    public ResultData list(@RequestBody PageInfo<SysUser> pageInfo){
        log.debug("分页查询用户："+pageInfo);
        return ResultData.success(sysUserService.listByPage(pageInfo));
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户",description = "更新用户")
    @OperateLog("更新用户信息")
    public ResultData save(@RequestBody SysUser sysUser){
        log.debug("保存用户："+sysUser);
        if (StringUtils.isBlank(sysUser.getId())){
            return ResultData.fail("用户id不能为空");
        }

        //用户名是否被使用
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SysUser::getId)
                .eq(SysUser::getUsername, sysUser.getUsername())
                .ne(SysUser::getId,sysUser.getId());
        if (sysUserService.exists(lambdaQueryWrapper)){
            return ResultData.fail("该用户名已被使用");
        }
        //更新用户
        //密码和生成日期不能该
        sysUser.setPassword(null);
        sysUser.setCreateTime(null);
        sysUser.setUpdateTime(new Date());
        sysUserService.updateById(sysUser);
        return ResultData.success();

    }

    @GetMapping("/delete/{id}")
    @Operation(summary = "删除用户",description = "删除用户")
    @OperateLog("删除用户")
    public ResultData delete(@PathVariable("id") String id){
        log.debug("删除用户："+id);
        //不能删除自己
        if (Objects.equals(id, StpUtil.getLoginId())){
            return ResultData.fail("不能删除自己");
        }
        sysUserService.removeById(id);
        return ResultData.success();
    }

    @GetMapping("/resetPassword/{id}")
    @Operation(summary = "重置密码",description = "重置密码")
    @OperateLog("重置密码")
    public ResultData resetPassword(@PathVariable("id") String id){
        log.debug("重置密码："+id);

        //重置密码
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setPassword(SaltMD5Util.generateSaltPassword("111111"));
        sysUserService.updateById(sysUser);
        return ResultData.success();
    }

    @PostMapping("/setRole")
    @Operation(summary = "设置角色",description = "设置角色")
    @OperateLog("用户授权")
    public ResultData setRole(@RequestBody Map<String,Object> map){
        log.debug("设置角色：{}",map);
        String userId = (String) map.get("userId");
        if (StringUtils.isBlank(userId)){
            return ResultData.fail("用户id不能为空");
        }
        List<String> roleIds = (List<String>) map.get("roleIds");
        return  userRoleService.setROle(userId,roleIds)?ResultData.success():ResultData.fail("设置角色失败");
    }

    @GetMapping("/changeStatus/{id}")
    @Operation(summary = "冻结/解冻",description = "修改状态")
    @OperateLog("冻结/解冻")
    public ResultData changeStatus(@PathVariable("id") String id){
        log.debug("修改状态："+id);
        if (StringUtils.equals(StpUtil.getLoginId().toString(),id)){
            return ResultData.fail("不能修改自己的状态");
        }
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null){
            return ResultData.fail("用户不存在");
        }
        sysUser.setStatus(sysUser.getStatus()==1?0:1);
        SysUser update = new SysUser();
        update.setId(id);
        update.setStatus(sysUser.getStatus());
        sysUserService.updateById(update);
        return ResultData.success();
    }

    @GetMapping("/profile")
    @Operation(summary = "个人资料",description = "个人资料")
    @OperateLog("查看个人资料")
    public ResultData profile(){
        //是否登录
        if (!StpUtil.isLogin()) {
            return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
        }
        String userId = StpUtil.getLoginId().toString();
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null){
            return ResultData.fail("用户不存在");
        }
        sysUser.setPassword(null);
        return ResultData.success(sysUser);
    }

    @PostMapping("/updateProfile")
    @Operation(summary = "更新个人基本资料",description = "更新个人基本资料")
    @OperateLog("更新个人信息")
    public ResultData updateProfile(@RequestBody RestInfoVo restInfoVo){
        log.debug("更新个人资料："+restInfoVo);
        //是否登录
        if (!StpUtil.isLogin()) {
            return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
        }
        String userId = StpUtil.getLoginId().toString();
        SysUser sysUser = restInfoVo.convertToBaseSysUser(userId);
        sysUserService.updateById(sysUser);
        return ResultData.success();
    }

    @PostMapping("/updatePassword")
    @Operation(summary = "更新个人密码",description = "更新个人密码")
    @OperateLog("更新个人密码")
    public ResultData updatePassword(@RequestBody RestInfoVo restInfoVo){
        log.debug("更新个人密码："+restInfoVo);
        //是否登录
        if (!StpUtil.isLogin()) {
            return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
        }
        //两次密码是否正确
        if (!StringUtils.equals(restInfoVo.getNewPassword(),restInfoVo.getConfirmPassword())){
            return ResultData.fail("两次密码不一致");
        }
        String userId = StpUtil.getLoginId().toString();
        if (!SaltMD5Util.verifySaltPassword(restInfoVo.getOldPassword(),sysUserService.getById(userId).getPassword())){
            return ResultData.fail("旧密码错误");
        }
        SysUser sysUser = restInfoVo.convertToPasswordSysUser(userId);
        sysUserService.updateById(sysUser);
        return ResultData.success();
    }






}

